import { Form, Input, Button, Checkbox } from 'antd-mobile'
import http from '../../api/index'
import Djs from '../../hooks/UseDjs'
import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import './login.css'
function Index() {
    const [num, fn, disable] = Djs()
  const [from] = Form.useForm()
  const [agreed, setAgreed] = useState(false)
  const [codeValue, setCodeValue] = useState('')
  // 保存待回显的验证码，等待倒计时结束后再写入表单
  const pendingCodeRef = useRef<string | null>(null)
  const nav = useNavigate()
  const yzm = async () => {
    const yzms = await from.validateFields(['phone'])
    const { data: res } = await http.post('/api/login', { phone: yzms.phone })
    console.log('获取验证码响应:', res.data)
    
    // 先缓存验证码并清空输入框，待倒计时结束后再回显
    pendingCodeRef.current = String(res.data ?? '')
    console.log('缓存验证码:', pendingCodeRef.current)
    setCodeValue('')  // 清空UI显示
    from.setFieldsValue({ code: '' })
    
    // 启动倒计时
    fn()
  }

  // 倒计时结束（按钮从禁用变为可用）后，将验证码回显到表单
  useEffect(() => {
    console.log('useEffect触发 - disable:', disable, 'pendingCode:', pendingCodeRef.current)
    if (!disable && pendingCodeRef.current) {
      const code = pendingCodeRef.current
      console.log('开始回显验证码:', code)
      setCodeValue(code)  // 更新UI显示
      from.setFieldsValue({ code })  // 更新表单数据
      console.log('验证码回显完成')
      pendingCodeRef.current = null
    }
  }, [disable, from])

  const onFinish = async (values: any) => {
    if (!agreed) {
      alert('请先同意服务协议和隐私政策')
      return
    }
    try {
      const { data: ref } = await http.post('/api/login', values)
  
      localStorage.setItem('token','rththt')
      localStorage.setItem('user', '小美')
    
      
      nav('/home')
    } catch (error) {
      console.error('登录失败:', error)
      alert('登录失败，请重试')
    }
  }

  return (
    <div className="login-container">
      {/* 应用标题区域 */}
      <div className="app-header">
        <div className="title-decoration">
          <div className="bubble bubble-1"></div>
          <div className="bubble bubble-2"></div>
          <div className="bubble bubble-3"></div>
        </div>
        <h1 className="app-title">妙手医生</h1>
      </div>

      {/* 表单区域 */}
      <div className="form-container">
        <Form
          form={from}
          layout='vertical'
          onFinish={onFinish}
        >
          <Form.Item
            name='phone'
            rules={[
              { 
                required: true, message: '手机号不能为空!' 
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式不正确!'
              },
            ]}
          >
            <div className="phone-input-wrapper">
              <span className="country-code">+86</span>
              <Input placeholder='输入手机号' className="phone-input" />
            </div>
          </Form.Item>
          
          <Form.Item
            name='code'
            rules={[
              {
                required: true, message: '验证码不能为空'
              },
            ]}
          >
            <div className="code-input-wrapper">
              <Input 
                placeholder='输入验证码' 
                className="code-input"
                value={codeValue}
                onChange={(val) => {
                  setCodeValue(val)
                  from.setFieldsValue({ code: val })
                }}
              />
              <Button 
                className="get-code-button" 
                onClick={yzm} 
                disabled={disable}
              >
                {disable ? `获取验证码(${num})` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>

      {/* 登录按钮 */}
      <div className="login-button-wrapper">
        <Button 
          className="login-button" 
          block 
          shape='rounded' 
          color='primary' 
          onClick={() => from.submit()}
          disabled={disable}
        >
          登录
        </Button>
      </div>

      {/* 协议条款 */}
      <div className="agreement-wrapper">
        <Checkbox 
          checked={agreed}
          onChange={setAgreed}
          className="agreement-checkbox"
        />
        <span className="agreement-text">
          已阅读并同意
          <a href="#" className="agreement-link">《妙手医生服务协议》</a>
          和
          <a href="#" className="agreement-link">《妙手医生隐私政策》</a>
          、
          <a href="#" className="agreement-link">《妙手医生儿童个人信息保护规则》</a>
        </span>
      </div>
    </div>
  )
}

export default Index
